import 'package:dartx/dartx.dart';
import 'package:get/get.dart';
import 'package:sgy_flutter/api_service.dart';
import 'package:sgy_flutter/ble/HardwareVersion.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/model/device_model.dart';
import 'package:sgy_flutter/model/dfu_info_model.dart';
import 'package:sgy_flutter/model/update_info.dart';

import '../model/device_type.dart';

extension DeviceModelFirmwareCheck on DeviceModel {

  /**
   * 只返回一个URL,返回空则表示不能降级 Pair<Version, Url>
   */
  Future<Pair<String?, String?>> fetchFallbackVersion(
      BleManager manager) async {
    final ApiService apiService = Get.find();
    final deviceInfo = await manager.deviceInfoService.readDeviceInfo();
    final resp = await manager.getFallbackVersion();
    final fallbackVersion = resp.fallbackVersion ?? '';
    String? url;
    if (deviceInfo.hardwareRevision == HardwareVersion.DLS_1_0.value) {
      final resp = await apiService.getFallbackVersion(
        hardwareVersion: deviceInfo.hardwareRevision ?? "",
        firmwareVersion: fallbackVersion,
        newVersion: true,
      );
      if (resp.data != null) {
        url = resp.data!;
      }
    } else if (deviceInfo.hardwareRevision
            ?.startsWith(HardwareVersion.JT_1_0.value) ==
        true) {
      final resp = await apiService.getFallbackVersion(
        hardwareVersion: deviceInfo.hardwareRevision ?? "",
        firmwareVersion: fallbackVersion,
        newVersion: true,
      );
      if (resp.data != null) {
        url = resp.data!;
      }
    } else if (deviceInfo.hardwareRevision
            ?.startsWith(HardwareVersion.AXO_2_0.value) ==
        true) {
      // AXO 硬件版本PM开头
      final resp = await apiService.getFallbackVersionOld(
          newVersion: true,
          deviceType: _deviceType(manager.deviceModel),
          firmwareVersion: fallbackVersion);
      if (resp.data != null) {
        url = resp.data!;
      }
    } else {
      final resp = await apiService.getFallbackVersionOld(
          newVersion: false,
          deviceType: _deviceType(manager.deviceModel),
          firmwareVersion: fallbackVersion);
      if (resp.data != null) {
        url = resp.data!;
      }
    }

    return Pair(fallbackVersion, url);
  }

  // 给旧的服务器接口用的
  String _deviceType(DeviceModel? model) {
    final name = model?.name ?? '';
    // AXO 硬件版本PM开头
    var type = "";
    if (name.contains("AXOCC") || name.contains("AXOcc")) {
      type = "AXOcc";
    } else if (name.contains("AXO") || name.contains("SPM2")) {
      type = "AXO";
    } else if (name.contains("DLS_L")) {
      type = "DLS_L";
    } else if (name.contains("DLS_R")) {
      type = "DLS_R";
    } else if (name.contains("AXPOWER")) {
      type = "AXPOWER";
    } else if (name.contains("HIFLOW")) {
      type = "HIFLOW";
    }
    return type;
  }
}
